package com.aivin.waterfallflow.tool;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


public final class ListPageUtil {
    private final CopyOnWriteArrayList<String> list;
    private final int pageSize;
    private final int pageCount ;
    private final int listSize ;
    private int pageIndex;

    public ListPageUtil(List<String> list, int pageSize) {
        if (null == list || 0 == list.size())  {
            throw new UnsupportedOperationException("List can not null!");
        }

        if (pageSize <=0 )   {
            throw new UnsupportedOperationException("Page size must be > 0");
        }

        this.list = new CopyOnWriteArrayList<>(list);
        this.listSize = list.size();
        this.pageSize = Math.min(pageSize, listSize);

        int tempPageCount =  listSize / pageSize;
        this.pageCount = listSize % pageSize == 0 ? tempPageCount : tempPageCount + 1;
        this.pageIndex = 0;
    }



    public List<String> nextPage()  {
        boolean hasNext = hasNext();
        if(!hasNext){
            return null ;
        }

        List<String> subList ;
        if (pageIndex == pageCount - 1) {
            subList = new ArrayList<>(list.subList(pageIndex * pageSize, listSize));
        }else  {
            subList = new ArrayList<>( list.subList(pageIndex * pageSize, (pageIndex + 1) * pageSize));
        }
        pageIndex++;
        return subList;
    }

    public boolean hasNext() {
        return pageIndex < pageCount;
    }

}